package com.letoken.platform.pub.token;

import com.letoken.platform.pub.util.AssertUtil;
import org.apache.commons.lang3.StringUtils;

import java.util.Base64;
import java.util.UUID;

/**
 * TokenUtil
 *
 */
public class TokenUtil {

    private final static String CHARSET = "UTF-8";

    /**
     * generateToken
     *
     * @param
     * @Return
     * @Exception
     */
    public static String generateToken() {
        StringBuffer tokenSb = new StringBuffer();
        tokenSb.append(UUID.randomUUID().toString().replaceAll("-", ""));
        tokenSb.append("-");
        tokenSb.append(System.currentTimeMillis());
        String tokenStr = tokenSb.toString();
        return getBase64Token(tokenStr);
    }

    /**
     * 根据用户ID生成Token
     *
     * @param userId
     * @return
     */
    public static String generateToken(Long userId) {
        AssertUtil.notNull(userId, "userId not null !");
        StringBuffer tokenSb = new StringBuffer();
        tokenSb.append(UUID.randomUUID().toString().replaceAll("-", ""));
        tokenSb.append("-");
        tokenSb.append(userId);
        tokenSb.append("-");
        tokenSb.append(System.currentTimeMillis());
        String tokenStr = tokenSb.toString();
        return getBase64Token(tokenStr);
    }

    /**
     * 根据TokenInfo生成Token
     *
     * @param tokenInfo
     * @return
     */
    public static String generateToken(TokenInfo tokenInfo) {
        AssertUtil.notNull(tokenInfo, "tokenInfo not null !");
        StringBuffer tokenSb = new StringBuffer();
        tokenSb.append(UUID.randomUUID().toString().replaceAll("-", ""));
        tokenSb.append("-");
        tokenSb.append(System.currentTimeMillis());
        tokenSb.append("-");
        tokenSb.append(tokenInfo.getId());
        if (tokenInfo.getRoleId() != null) {
            tokenSb.append("-");
            tokenSb.append(tokenInfo.getRoleId());
        }
        if (tokenInfo.getPartnerId() != null) {
            tokenSb.append("-");
            tokenSb.append(tokenInfo.getPartnerId());
        }
        String tokenStr = tokenSb.toString();
        return getBase64Token(tokenStr);
    }

    private static String getBase64Token(String str) {
        try {
            return Base64.getEncoder().encodeToString(str.getBytes(CHARSET));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 根据Token解密UserId
     *
     * @param token
     * @return
     */
    public static Long getUserIdByToken(String token) {
        try {
            if (StringUtils.isNotBlank(token)) {
                String deToken = new String(Base64.getDecoder().decode(token), CHARSET);
                String[] arr = deToken.split("-");
                String userIdStr = arr[1];
                return Long.parseLong(userIdStr);
            }
            return null;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 根据Token解密TokenInfo，注意，必须是以TokenInfo加密的才能解密成TokenInfo，否则返回null
     *
     * @param token
     * @return
     */
    public static TokenInfo getTokenInfoByToken(String token) {
        try {
            if (StringUtils.isNotBlank(token)) {
                String deToken = new String(Base64.getDecoder().decode(token), CHARSET);
                String[] arr = deToken.split("-");
                TokenInfo tokenInfo = new TokenInfo();
                if (arr.length >= 3) {
                    String userIdStr = arr[2];
                    Long id = Long.parseLong(userIdStr);
                    tokenInfo.setId(id);
                }
                if (arr.length >= 4) {
                    String roleIdStr = arr[3];
                    Long roleId = roleIdStr == null ? null : Long.parseLong(roleIdStr);
                    tokenInfo.setRoleId(roleId);
                }
                if (arr.length >= 5) {
                    String partnerIdStr = arr[4];
                    Long partnerId = partnerIdStr == null ? null : Long.parseLong(partnerIdStr);
                    tokenInfo.setPartnerId(partnerId);
                }
                return tokenInfo;
            }
            return null;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

//    public static void main(String[] args) throws Exception {
//        long userId = 999999999999999999L;
//        String token = generateToken(userId);
//        System.out.println(token);
//        String deToken = new String(Base64.getDecoder().decode(token), CHARSET);
//        System.out.println(deToken);
//
////        Long deUserId = getUserIdByToken(token);
////        System.out.println(deUserId);
////
////        TokenInfo userTokenInfo = new TokenInfo();
////        userTokenInfo.setId(20072L);
////        String userToken = generateToken(userTokenInfo);
////        System.out.println(userToken);
////
////        TokenInfo tokenInfo = new TokenInfo();
////        tokenInfo.setId(210005L);
////        tokenInfo.setRoleId(100001L);
////        tokenInfo.setPartnerId(100000L);
////        String managerToken = generateToken(tokenInfo);
////        System.out.println(managerToken);
////
////        tokenInfo = getTokenInfoByToken("NDIzYWFkNzI0MTMyNGI0YzkxYjU1NjllNDQ1ZThiNzItMTU0NjQyMTY5NDQ5MS0yMTMwNS0xMDAyNC0xMDAwMDA=");
////        System.out.println(tokenInfo);
//    }
}
